#pragma once

#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#include <cstring>
#include <memory>
#include <string>
#include <sys/types.h>
#include <sys/wait.h>
#include <signal.h>
#include <functional>

#include "Log.hpp"
#include "Common.hpp"
#include "InetAddr.hpp"
#include "ThreadPool.hpp"

#define BACKLOG 8

static uint16_t gport = 8081;
using handler_t = std::function<std::string (std::string&)>;


using namespace LogModule;
using namespace ThreadPoolModule;

class TcpServer
{   
    using task_t = std::function<void()>;

    struct ThreadData
    {
        int sockfd;
        TcpServer *self;
    };

public:
    TcpServer(handler_t handler, int port = gport) :_handler(handler) ,_port(port), _isrunning(false)
    {
    }

    void InitServer()
    {
        // 1. 套接字创建(流式套接字 -- socket stream)
        _listensockfd = ::socket(AF_INET, SOCK_STREAM, 0); //_listensockfd属于一个拉客的服务员，下一个sockfd才是要提供服务的
        if (_listensockfd < 0)
        {
            LOG(LogLevel::FATAL) << "socket error";
            Die(SOCKET_ERR);
        }
        LOG(LogLevel::INFO) << "socket create success, sockfd is : " << _listensockfd;
        // 对象填充
        struct sockaddr_in local;
        memset(&local, 0, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(gport);
        local.sin_addr.s_addr = INADDR_ANY;
        // 2. bind
        int n = ::bind(_listensockfd, CONV(&local), sizeof(local));
        if (n < 0)
        {
            LOG(LogLevel::FATAL) << "bind error";
            Die(BIND_ERR);
        }
        LOG(LogLevel::INFO) << "bind success, sockfd is : " << _listensockfd;

        // 3. cs, tcp是面向连接的，就需要tcp随时地等待被连接
        //   tcp需要将socket设置为监听状态
        n = ::listen(_listensockfd, BACKLOG);
        if (n < 0)
        {
            LOG(LogLevel::FATAL) << "listen error";
            Die(LISTEN_ERR);
        }
        LOG(LogLevel::INFO) << "listen success, sockfd is : " << _listensockfd;

        //::signal(SIGCHLD, SIG_IGN);
    }
    void HandlerRequest(int sockfd)
    { // TCP也是全双工的
        LOG(LogLevel::INFO) << "HandlerRequest, new sockfd is : " << sockfd;
        // TCP面向字节流，和文件更类似
        char inbuffer[4096];
        std::string package;
        //该任务属于长任务
        while (true)
        {   
            ssize_t n = ::recv(sockfd, inbuffer, sizeof(inbuffer) - 1, 0);     //采用recv来代替
            
            if (n > 0)
            {
                inbuffer[n] = 0;
                //std::cout << std::string(inbuffer)<<std::endl;
                LOG(LogLevel::INFO) << inbuffer;
                package += inbuffer;        //

                std::string cmd_result = _handler(package);    //执行我们在最上层传递的任务

                if(cmd_result.empty()) continue;    //TODO

                ::send(sockfd, cmd_result.c_str(), cmd_result.size(), 0); //采用send来代替
            }
            else if (n == 0) // read若return 0时，表示client退出
            {
                LOG(LogLevel::INFO) << "client quit: " << sockfd;
                break;
            }
            else // 读取失败
            {
                break;
            }
        }
        ::close(sockfd);
    }

    static void *ThreadEntry(void *args)
    {   
        //线程让自己设置为分离
        pthread_detach(pthread_self());     //直接让线程分离，让线程自己管理自己
        ThreadData *data = (ThreadData *)args;
        data->self->HandlerRequest(data->sockfd);
        return nullptr;
    }

    void Start()
    {
        _isrunning = true;
        while (_isrunning)
        {
            // 不能直接读取数据，需要获取新连接：
            struct sockaddr_in peer;
            socklen_t peerlen = sizeof(peer); // 这个地方一定要注意，要提供sockaddr_in的结构体大小

            LOG(LogLevel::DEBUG) << "accept ing ...";

            // accept第二个参数都属于输出型参数，存放着client的信息
            int sockfd = ::accept(_listensockfd, CONV(&peer), &peerlen); // 这个sockfd才是提供通信服务的
            if (sockfd < 0)
            {
                // sockfd，表示获取未成功，重新获取其他的新连接
                LOG(LogLevel::WARNING) << "accept error : " << strerror(errno);
                continue;
            }

            // 获取成功：
            LOG(LogLevel::INFO) << "listen success, new sockfd is : " << sockfd;
            //  打印客户端的信息：
            InetAddr addr(peer);
            LOG(LogLevel::INFO) << "client info: " << addr.Addr();

            ThreadPool<task_t>::getInstance()->Equeue([this, sockfd](){
                this->HandlerRequest(sockfd);
            });
        }
    }
    void Stop()
    {
        _isrunning = false;
    }
    ~TcpServer()
    {
    }

private:
    int _listensockfd;
    uint16_t _port;
    bool _isrunning;

    //处理上层任务的入口
    handler_t _handler;
};
